package org.wzy.spring.framework.webmvc.demo.controller;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.wzy.spring.framework.annotation.Autowired;
import org.wzy.spring.framework.annotation.Controller;
import org.wzy.spring.framework.annotation.RequestMapping;
import org.wzy.spring.framework.annotation.RequestParam;
import org.wzy.spring.framework.webmvc.demo.service.IDemoService;
import org.wzy.spring.framework.webmvc.demo.service.IUserService;
import org.wzy.spring.framework.webmvc.servlet.ModelAndView;

import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * DemoController, 测试 IOC 容器是否初始化成功, 所有的依赖是否全部注入成功
 *
 * @author wzy_h
 * @version v_1.0
 * @date 2018/5/19 16:31
 * @since 1.8
 */
@Controller
@RequestMapping("/demo")
public class DemoController {

    private Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IDemoService demoService;

    @Autowired
    private IUserService userService;

    @RequestMapping("/get*")
    public ModelAndView getSth(HttpServletResponse response, @RequestParam("userName") String userName, @RequestParam("data") String data) {
        demoService.get(userName);
        demoService.add(userName);

        Map<String, String> dataMap = new HashMap<>(2);
        dataMap.put("userName", userName);
        dataMap.put("data", data);
        return new ModelAndView("first.html", dataMap);
    }

    /**
     * 声明了 {@code @RequestMapping} 注解却未提供 url 映射, 则不会被纳入 Spring IOC 容器的管理.
     *
     * @param response response
     * @return ModelAndView
     * @author 王政豫
     * @date 2018/8/30 10:29
     */
    @RequestMapping
    public ModelAndView requestWithoutUrlInjectTest(HttpServletResponse response) {
        Map<String, String> dataMap = new HashMap<>(2);
        dataMap.put("userName", "zhangsan");
        dataMap.put("data", "没有数据");
        return new ModelAndView("first.html", dataMap);
    }

    public void test(String name) {
        userService.saveUser(name);
        String result = demoService.get(name);
        logger.error("打印 DemoController 中的 IDemoService 对象所在的内存地址={}, result={}", demoService, result);
    }
}
